package com.cskaoyan.mall.pay.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.pay.constants.PayRetCode;
import com.cskaoyan.mall.pay.form.PaymentRequest;
import com.cskaoyan.mall.pay.service.PayCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/cashier")
@Slf4j
public class PayController {

    @Autowired
    PayCoreService payCoreService;


    @PostMapping("/pay")
    public ResponseData prePay(@Validated @RequestBody PaymentRequest request, HttpServletRequest httpServletRequest) {
        log.info("支付表单数据:{}", request);
        String userInfo = httpServletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = object.getLong("uid");
        request.setUserId(uid);
        request.setSubject("csmall_order");

        String qrCode = payCoreService.aliPay(request);
        String codeUrl = "http://localhost:8104/image/" + qrCode;
        return new ResponseUtil<>().setData(codeUrl);
    }


    @GetMapping("/queryStatus")
    public ResponseData checkPay(@NotNull String orderId) {
        boolean success = payCoreService.queryAlipayRet(orderId);
        if (success) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(PayRetCode.PAY_FAILED.getMsg());
    }


}
